library(ggplot2)
library(extrafont)

rm(list = ls())
setwd("")

S_F <- 5
T <- 3
R_F <- .75
A <- 1/4
S_B <- 5
VSTAR <- .002
F <- 2 #Number of follow-up surveys


# RHO TO COST MAP
rho.cost.map <- function(rho) 4 * ((1-rho^2)/VSTAR) * (S_F*F + (T + S_B)/(A*R_F))
rho.cost.map(0)

no.item <- data.frame(x = 0, y = rho.cost.map(0))
one.item <- data.frame(x = .5, y = rho.cost.map(.5))
many.items <- data.frame(x = .9, y = rho.cost.map(.9))

g <- ggplot(data.frame(x=c(0, .999)), aes(x)) +
  stat_function(fun=rho.cost.map) +
  scale_y_continuous(labels = scales::dollar) +
  geom_point(data = no.item, aes(x=x,y=y), color = 'red') +
  geom_text(data = no.item, aes(x = x + .02, y = y - 8000, label = "No Items", color = 'red')) +
  geom_point(data = one.item, aes(x=x,y=y), color = 'red') +
  geom_text(data = one.item, aes(x = x - .08, y = y, label = "One Item", color = 'red')) +
  geom_point(data = many.items, aes(x=x,y=y), color = 'red') +
  geom_text(data = many.items, aes(x = x - .12, y = y, label = "Multiple Items", color = 'red')) +
  theme_bw() +
  ylab("Variable Cost (Treatment and Surveys)") +
  xlab(expression(paste("Stability Between Baseline and Follow-Up (",
                        rho,
                        ")")
                  )
       ) +
  theme(legend.position="none", text = element_text(family = 'Verdana'))
g
#Figure 4: How Experiment Costs Decrease with Higher Stability Between Baseline and Follow-up Outcome Measurements
ggsave("output/rho_cost_map.tiff", g, width = 8, height = 3.5, units = 'in')

# R_F TO COST MAP
R_F <- NULL
rho <- .9
R_F.cost.map <- function(R_F) 4 * ((1-rho^2)/VSTAR) * (S_F*F + (T + S_B)/(A*R_F))

phone.no.panel <- data.frame(x = .07, y = R_F.cost.map(.07))
phone.panel <- data.frame(x = .35, y = R_F.cost.map(.35))
online <- data.frame(x = .75, y = R_F.cost.map(.75))

ggplot(data.frame(x=c(.06, 1)), aes(x)) +
  stat_function(fun=R_F.cost.map) +
  scale_x_continuous(limits = c(0,1)) +
  scale_y_continuous(labels = scales::dollar, limits = c(0, 220000)) +
  geom_point(data = phone.no.panel, aes(x=x,y=y), color = 'red') +
  geom_text(data = phone.no.panel, aes(x = x + .1, y = y, label = "Example Phone\nOne Interview R", color = 'red')) +
  geom_point(data = phone.panel, aes(x=x,y=y), color = 'red') +
  geom_text(data = phone.panel, aes(x = x + .1, y = y + 19000, label = "Example Phone\nSecond Interview R", color = 'red')) +
  geom_point(data = online, aes(x=x,y=y), color = 'red') +
  geom_text(data = online, aes(x = x, y = y + 20000, label = "Example Online Panel\nSecond Interview R", color = 'red')) +
  theme_bw() +
  theme(legend.position="none", text = element_text(family = 'Verdana')) + 
  ylab("Variable Cost (Treatment and Surveys)") +
  xlab(expression('Response Rate to Follow-Up (R)'))
#Figure 3: How Experiment Costs Decrease with Higher Survey Response Rates
ggsave("output/R_F_cost_map.tiff", width = 8, height = 3.5)